# coding: utf-8

from flask import current_app
from flask import render_template, redirect, request, url_for, flash

from .. import db
from . import msg_bp
from .models import SMSTemplate, SMSLog
from .forms import SMSTemplateForm, SearchSMSLogForm


@msg_bp.route('/sms_template_list', methods=['GET', 'POST'])
def sms_template_list():
    """
    短信模板列表
    """
    page = request.args.get('page', 1, type=int)
    pagination = SMSTemplate.query.order_by(SMSTemplate.id.asc()).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    sms_templates = pagination.items
    return render_template(
        'sms_template_list.html',
        sms_templates=sms_templates,
        pagination=pagination,
        page=page,
    )


@msg_bp.route('/sms_template_add', methods=['GET', 'POST'])
def sms_template_add():
    """
    新增短信模板
    """
    form = SMSTemplateForm()
    if form.validate_on_submit():
        sms_template = SMSTemplate()
        form.populate_obj(sms_template)
        db.session.add(sms_template)
        flash('新增短信模板成功')
        return redirect(url_for('msg_bp.sms_template_list'))
    return render_template('sms_template_add.html', form=form)


@msg_bp.route('/sms_template_edit/<int:sms_template_id>', methods=['GET', 'POST'])
def sms_template_edit(sms_template_id):
    """
    编辑短信模板
    """
    sms_template = SMSTemplate.query.get_or_404(sms_template_id)
    form = SMSTemplateForm()
    if form.validate_on_submit():
        form.populate_obj(sms_template)
        flash('修改成功')
        return redirect(url_for('msg_bp.sms_template_list'))

    form = SMSTemplateForm(obj=sms_template)
    return render_template('sms_template_edit.html', form=form)


@msg_bp.route('/sms_log', methods=['GET', 'POST'])
def sms_log_list():
    """
    短信发送记录
    """
    form = SearchSMSLogForm(formdata=request.form or request.args)

    log_query = SMSLog.query
    url_kwargs = {}
    if form.validate():
        _, url_kwargs = form.generate_kwargs()

        log_query = SMSLog.generate_list_query_condition(
            args=url_kwargs,
            query=log_query
        )
    page = request.args.get('page', 1, type=int)
    pagination = log_query.order_by(SMSLog.created_at.desc()).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    logs = pagination.items

    return render_template(
        'sms_log_list.html',
        form=form,
        logs=logs,
        pagination=pagination,
        url_kwargs=url_kwargs,
    )
